package zky410;

public class test3 {
    public static class ListNode {
    int val;
    ListNode next = null;
    public ListNode(int val) {
      this.val = val;
    }
  }

    public static void main(String[] args) {
        ListNode n1 = new ListNode(1);
        ListNode n2 = new ListNode(0);
        ListNode n3 = new ListNode(0);
        ListNode n4 = new ListNode(9);
        ListNode n5 = new ListNode(9);
        //ListNode n6 = new ListNode(6);
        n1.next = n2;
        n2.next = n3;
        n4.next = n5;
        //n5.next = n6;
        ListNode listNode = minusList(n1, n4);
        System.out.println(listNode.val);
        System.out.println(listNode.next.val);
        System.out.println(listNode.next.next.val);
        System.out.println(listNode.next.next.next.val);

    }
    public static ListNode minusList (ListNode minuendList, ListNode subtrahendList) {
        // write code here
        ListNode l11 = reverse(minuendList);
        ListNode l22 = reverse(subtrahendList);
        if(l11 != null){
            l11.val = -l11.val;
        }
        ListNode p1 = l11;
        ListNode p2 = l22;
        int flag = 0;
        ListNode dummy = new ListNode(-1);
        ListNode p = dummy;
        while(p1 != null || p2 != null){
            int temp = flag;
            if(p1 != null ){
                temp += p1.val;
                p1 = p1.next;
            }
            if(p2!=null){
                temp += p2.val;
                p2 = p2.next;
            }
            if(temp>9){
                temp -= 10;
                flag = 1;
            }else {
                flag = 0;
            }
            ListNode node = new ListNode(temp);
            p.next = node;
            p = p.next;
        }
        if(flag ==1){
            ListNode node = new ListNode(1);
            p.next = node;
        }
        ListNode res = reverse(dummy.next);
        while(res.val == 0){
            res = res.next;
        }
        return res;
    }


    public static ListNode reverse(ListNode head){
        ListNode newhead = null;
        boolean flag = true;
        if(head.val < 0){
            flag = false;
            head.val = -head.val;
        }
        while(head!=null){
            ListNode temp = head.next;
            head.next = newhead;
            newhead = head;
            head = temp;
        }
        if(!false){
            newhead.val = -newhead.val;
        }
        return newhead;
    }
}
